package com.steven.logserver.config;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryNTimes;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

/**
 *  Zookeeper配置
 *
 * @author qinxh
 * @date 2020/08/31
 */
@Configuration
public class ZookeeperConfig {

    private static CuratorFramework client = null;

    private static RetryPolicy retryPolicy = null;

    @Value("${log.netty.zk.server.path}")
    private String zkServerPath;

    @Value("${log.netty.server.node.Path}")
    private String nodePath;

    @Value("${log.netty.server.workspace}")
    private String workspace;

    @Value("${log.netty.zk.server.tryTimes}")
    private Integer tryTimes;

    @Value("${log.netty.zk.server.between.retries}")
    private Integer sleepMsBetweenRetries;

    @Value("${log.netty.zk.server.session.timeout}")
    private Integer sessionTimeout;

    @Value("${log.netty.zk.server.connection.timeout}")
    private Integer connectionTimeout;

    /**
     * 初始化
     */
    @PostConstruct
    public void init (){

        // 使用重试策略创建Zk客户端
        retryPolicy = new RetryNTimes(tryTimes, sleepMsBetweenRetries);
        client = CuratorFrameworkFactory.builder()
                .connectString(zkServerPath)
                .sessionTimeoutMs(sessionTimeout)
                .connectionTimeoutMs(connectionTimeout)
                .retryPolicy(retryPolicy)
                //指定命名空间后，client 的所有路径操作都会以/workspace 开头
                .namespace(workspace).build();

        //开启连接
        client.start();
        System.out.println("zookeeper 初始化完成...");
    }

    public static CuratorFramework getClient (){

        return client;
    }

    public static RetryPolicy getRetryPolicy(){

        return retryPolicy;
    }

}
